<template>

    <div class="table">
        <div class="container">
            <div class="handle-box">
                <el-button size="small" type="primary" @click="dialogFormVisible = true">{{$t('AddRole')}}</el-button>
                <el-button size="small" type="danger" @click="batchDelRole">{{$t('DeleteRole')}}</el-button>
            </div>
            <el-table :data="tableData" align="center" @selection-change="selsChange" stripe border
                      style="width:100%;margin-top: 10px">
                <el-table-column type="selection" width="65"></el-table-column>
                <el-table-column prop="roleId" width="150" label="ID"></el-table-column>
                <el-table-column prop="roleName" :label="$t('RoleName')"></el-table-column>
                <el-table-column prop="roleRemark" :label="$t('Remark')"></el-table-column>
                <el-table-column prop="roleId" :label="$t('Operation')">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="getAuthByRole(scope.row)">{{$t('EditAuth')}}
                        </el-button>
                        <el-button type="danger" size="mini" @click="deleteRole(scope.row.roleId)">{{$t('Delete')}}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :title="$t('EditAuth')" :visible.sync="authTreeDialogVisible" width="50%"
                   :before-close="handleAuthTreeClose">
            <el-scrollbar>
                <div style="height: 350px">

                    <!--<el-col :span="4">-->
                    <!--<el-tag>已选择:{{roleName}}</el-tag>-->
                    <!--</el-col>-->
                    <el-col :span="12">
                        <el-button-group>
                            <el-button size="small" type="primary" @click="grantOperToRole">{{$t('Save')}}</el-button>
                            <el-button size="small" v-if="selectAllTreeFlag" type="primary" @click="selectAllTree">
                                {{$t('SelectAll')}}
                            </el-button>
                            <el-button size="small" v-if="cancelAllTreeFlag" type="primary" @click="cancelAllTree">
                                {{$t('CancelAll')}}
                            </el-button>
                            <el-button size="small" type="info" @click="expandAllNodes">{{$t('Expand')}}</el-button>
                            <el-button size="small" type="info" @click="foldAllNodes">{{$t('Fold')}}</el-button>
                        </el-button-group>
                    </el-col>
                    <el-col>
                        <div>
                            <elTree ref="tree" v-bind:treeData="treeData"></elTree>
                        </div>
                    </el-col>
                </div>
            </el-scrollbar>

        </el-dialog>
        <el-dialog :title="$t('AddRole')" :visible.sync="dialogFormVisible" width="50%" :before-close="handleClose">
            <el-form :model="roleForm" :rules="rules" ref="roleForm">
                <el-form-item :label="$t('RoleName')" :label-width="formLabelWidth" prop="name">
                    <el-input size="small" v-model="roleForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item :label="$t('Remark')" :label-width="formLabelWidth" prop="remark">
                    <el-input size="small" v-model="roleForm.remark" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm('roleForm')">{{$t('Confirm')}}</el-button>
                <el-button size="small" @click="resetForm('roleForm')">{{$t('Cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>


</template>

<script>
    import elTree from '../common/ElTree.vue'

    export default {
        data() {
            return {
                treeData: [],
                dialogFormVisible: false,
                authTreeDialogVisible: false,
                roleForm: {
                    name: '',
                    remark: ''
                },
                rules: {
                    name: [{required: true, message: '请输入角色名', trigger: 'change'}]
                },
                formLabelWidth: '120px',
                roleName: '',
                tableData: [],
                selectedRole: [],//选中的角色
                editRole: {
                    roleId: "",
                    roleName: "",
                },
                selectAllTreeFlag: true,
                cancelAllTreeFlag: false,
                // table : {
                //     data : [],
                //     currentPage : 1,
                //     pageSize : 10,
                //     total : 0
                // },
            }
        },

        methods: {
            handleClose(done) {
                this.dialogFormVisible = false;
            },
            handleAuthTreeClose(done) {
                this.authTreeDialogVisible = false;
            },
            updateName(name) {
                this.roleName = name
            },
            selsChange(sels) {
                //被选中的行组成数组
                let tmpSel = [];
                for (let index in sels) {
                    tmpSel.push(sels[index].roleId);
                }
                this.selectedRole = tmpSel;
            },
            getRoleData() {
                let _self = this;
                this.$http
                    .get('sys/findAllRoles')
                    .then(function (response) {
                        _self.tableData = response.data.result;
                    })
                    .catch(function (error) {
                        console.log(error)
                    })
            },
            getTreeData() {
                let result = [];
                this.$http
                    .get('sys/findAllOpers')
                    .then(function (response) {
                        // console.log(response.data);
                        let list = response.data.result;
                        let idstr = [];
                        let pidstr = [];
                        for (let i = 0; i < list.length; i++) {
                            idstr.push(list[i].id);
                            pidstr.push(list[i].parent);
                            list[i].label = list[i].text;
                            list[i].isLeaf = true;
                        }
                        let temp = {};
                        for (let i = 0; i < list.length; i++) {
                            temp[idstr[i]] = list[i];//将nodes数组转成对象类型
                        }
                        for (let j = 0; j < list.length; j++) {

                            let tempVp = temp[pidstr[j]];//获取每一个子对象的父对象
                            if (tempVp) {
                                //判断父对象是否存在，如果不存在直接将对象放到第一层
                                tempVp.isLeaf = false;
                                if (!tempVp['children']) tempVp['children'] = []; //如果父元素的nodes对象不存在，则创建数组
                                tempVp['children'].push(list[j]);//将本对象压入父对象的nodes数组
                            } else {
                                result.push(list[j]); //将不存在父对象的对象直接放入一级目录
                            }
                        }

                    })
                    .catch(function (error) {
                        console.log(error);
                    })
                this.treeData = result
            },
            expandAllNodes() {
                for (let i = 0; i < this.$refs["tree"].$children[0].store._getAllNodes().length; i++) {
                    this.$refs["tree"].$children[0].store._getAllNodes()[i].expanded = true;
                }
            },
            foldAllNodes() {
                for (let i = 0; i < this.$refs["tree"].$children[0].store._getAllNodes().length; i++) {
                    this.$refs["tree"].$children[0].store._getAllNodes()[i].expanded = false;
                }
            },
            selectAllTree() {
                let idstr = [];
                for (let i = 0; i < this.treeData.length; i++) {
                    idstr.push(this.treeData[i].id);
                }
                this.$refs["tree"].$children[0].setCheckedKeys(idstr);//全选
                this.selectAllTreeFlag = false;
                this.cancelAllTreeFlag = true;
            },
            cancelAllTree() {
                this.$refs["tree"].$children[0].setCheckedKeys([]);//全不选
                this.selectAllTreeFlag = true;
                this.cancelAllTreeFlag = false;
            },
            grantOperToRole() {
                let _self = this;
                let selectOpers = this.$refs["tree"].$children[0].getCheckedKeys();
                selectOpers = selectOpers.concat(this.$refs["tree"].$children[0].getHalfCheckedKeys());
                _self.$http
                    .post('sys/grantOperToRole',
                        {
                            roleId: _self.editRole.roleId,
                            rname: _self.editRole.roleName,
                            opers: JSON.stringify(selectOpers)
                        }
                    )
                    .then(function (response) {
                        if (response.data.result) {
                            _self.$message({
                                message: _self.$t('Success'),
                                type: 'success'
                            })
                        } else {
                            _self.$message.error(_self.$t('Failed'));
                        }
                    })
                    .catch(function (error) {
                        console.log(error)
                    })
            },
            getAuthByRole(row) {
                let _self = this;
                _self.editRole.roleId = row.roleId;
                _self.editRole.roleName = row.roleName;
                _self.authTreeDialogVisible = true;
                _self.selectAllTreeFlag = true;
                _self.cancelAllTreeFlag = false;
                _self.$http
                    .get('sys/findAuthByRole', {
                            params: {
                                rid: row.roleId
                            }
                        }
                    )
                    .then(function (response) {
                        let tree = _self.$refs["tree"].$children[0];
                        tree.setCheckedKeys([]);//清空
                        let checkedNode = [];//需要勾选的节点
                        for (let index  in response.data.result) {
                            let key = response.data.result[index];
                            let node = tree.getNode(key);
                            if (node.isLeaf)
                                checkedNode.push(key);
                        }

                        tree.setCheckedKeys(checkedNode);//清空
                    })
                    .catch(function (error) {
                        console.log(error)
                    })
            },
            deleteRole(rid) {
                let _self = this;
                this.$confirm(_self.$t('IsDelete'), _self.$t('Tip'), {
                    confirmButtonText: _self.$t('Confirm'),
                    cancelButtonText: _self.$t('Cancel'),
                    type: 'warning'
                }).then(() => {
                    _self.$http
                        .post('sys/deletesysRole',
                            {
                                rid: rid
                            }
                        )
                        .then(function (response) {
                            if (response.data.result == true) {
                                _self.$message({
                                    message: _self.$t('Success'),
                                    type: 'success'
                                })
                                _self.getRoleData()
                            } else {
                                _self.$message.error(_self.$t('Failed'))
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                        })
                }).catch(() => {

                });


            },
            batchDelRole() {
                let _self = this;
                this.$confirm(_self.$t('IsDelete'), _self.$t('Tip'), {
                    confirmButtonText: _self.$t('Confirm'),
                    cancelButtonText: _self.$t('Cancel'),
                    type: 'warning'
                }).then(() => {
                    _self.$http
                        .post('sys/batchDelsysRole', {
                            rid: JSON.stringify(_self.selectedRole)
                        })

                        .then(function (response) {
                            if (response.data.result == true) {
                                _self.$message({
                                    message: _self.$t('Success'),
                                    type: 'success'
                                })
                                _self.getRoleData()
                            } else {
                                _self.$message.error(_self.$t('Failed'))
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                        })
                }).catch(() => {

                });

            },
            submitForm(formName) {
                let _self = this
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        _self.$http
                            .post('sys/addsysRole',
                                {
                                    rolename: _self.roleForm.name,
                                    roleremark: _self.roleForm.remark
                                }
                            )
                            .then(function (response) {
                                _self.dialogFormVisible = false
                                if (response.data.result) {
                                    _self.$message({
                                        message: _self.$t('Success'),
                                        type: 'success'
                                    })
                                    _self.getRoleData()
                                } else {
                                    _self.$message.error(_self.$t('Failed'))
                                }
                            })
                            .catch(function (error) {
                                console.log(error)
                            })
                    } else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },
            resetForm(formName) {
                this.$refs[formName].resetFields()
                this.dialogFormVisible = false
            }
        },
        components: {
            elTree,
        },

        created: function () {
            //这个是钩子函数
            let _self = this
            _self.getTreeData();
            _self.getRoleData();
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }
</style>
